package cn.sxw.ld.common.controller;

import cn.sxw.ld.common.dto.R;
import cn.sxw.ld.common.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.UUID;

/**
 * 通用 controller，图片上传下载
 */
@RequestMapping("/common")
@RestController
@Slf4j
public class CommonController {

    @Value("${ling-dan-cat.imagePath}")
    private String imagePath;


    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {

        // 判断文件是否为空
        if (file.isEmpty()) {
            return R.error("上传的文件为空");
        }

        // 判断文件大小
        long fileSize = file.getSize();
        long maxSize = 10 * 1024 * 1024; // 最大支持10MB
        if (fileSize > maxSize) {
            return R.error("上传的文件大小超出限制");
        }

        // 判断文件类型
        String contentType = file.getContentType();
        String[] allowedTypes = {"image/jpeg", "image/png", "image/gif"};
        boolean isAllowedType = false;
        for (String type : allowedTypes) {
            if (contentType.equals(type)) {
                isAllowedType = true;
                break;
            }
        }
        if (!isAllowedType) {
            return R.error("不支持的文件类型");
        }

        // 判断目录是否存在
        File dir = new File(imagePath);
        if (!dir.exists()) {
            boolean b = dir.mkdirs();// 创建多级目录
            if (!b) {
                throw new CustomException("目录创建失败");
            }
        }

        // 处理文件名
        String originalFilename = file.getOriginalFilename();
        assert originalFilename != null;
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID() + suffix;

        // 保存文件
        try {
            file.transferTo(new File(imagePath + File.separator + fileName));
        } catch (IOException e) {
            log.error("文件上传失败", e);
            return R.error("文件上传失败");
        }

        return R.success(fileName);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        try {
            // 获取文件路径
            File file = new File(imagePath + File.separator + name);
            if (!file.exists()) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            }

            // 设置响应头
            response.setContentType(Files.probeContentType(file.toPath()));
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(name, "UTF-8"));

            // 输出文件内容
            try (FileInputStream fis = new FileInputStream(file);
                 ServletOutputStream sos = response.getOutputStream()) {
                byte[] buffer = new byte[1024];
                int len;
                while ((len = fis.read(buffer)) != -1) {
                    sos.write(buffer, 0, len);
                }
            }
        } catch (Exception e) {
            log.error("文件下载失败", e);
        }
    }
}
